<template>
  <mu-col span="12">
    <mu-col span="12" v-show="$com.isbool(openEdit)">
      <input style="display: none" multiple="multiple" type="file" ref="fileInput" @change="upload(name)">
      <mu-button @click="selectPic(name)" color="primary">
        选择
        <mu-icon right value="cloud_upload"></mu-icon>
      </mu-button>
    </mu-col>
    <mu-col span="12">
      <mu-grid-list style="display: flex;flex-wrap: nowrap;overflow-x: auto;" :cols="4" v-if="viewPic !== []">
        <mu-grid-tile v-for="item,index in viewPic" :key="index">
          <img alt="image" :src="url + item"/>
          <mu-button @click="deletePic(index)" slot="action" icon  v-show="$com.isbool(openEdit)">
            <mu-icon value="delete"></mu-icon>
          </mu-button>
          <mu-button @click="()=>{openDialog=true;curPic=url + item}" slot="title" icon  >
            <mu-icon value="visibility"></mu-icon>
          </mu-button>
        </mu-grid-tile>
      </mu-grid-list>
    </mu-col>
    <!--    隐藏项目-->
    <mu-dialog title="预览" :open.sync="openDialog" scrollable>
      <img :src="curPic" alt="">
      <mu-button slot="actions" flat color="primary" @click="openDialog = false">关闭</mu-button>
    </mu-dialog>
  </mu-col>
</template>

<script>
import api from '@/assets/js/api'

export default {
  name: "pics",
  props: {
    name: '',
    pics: '',
    openEdit: ''
  },
  data () {
    return {
      openDialog:  false,
      viewPic:  this.pics,
      url: api.getUrl(),
      curPic:''
    }
  },
  mounted () {
    // this.viewPic = api.getUrl() + this.value
  },
  methods: {
    selectPic (refName) {
      console.log(this.$refs.fileInput)
      this.$refs.fileInput.dispatchEvent(new MouseEvent("click"));
    },
    upload (refName) {
      let _this = this
      let files = this.$refs.fileInput.files;
      console.log(files)
      for (let i in files){
        let file = files[i]
        api.upload(file, function (res) {
          if (res.s == 1) {
            let url = res.d
            _this.viewPic.push(url)
            _this.$emit('update:pics', _this.viewPic)
          }
        })
      }

    },
    deletePic (index) {
      this.viewPic = arrayDelIndex(this.viewPic, index)
      this.$emit('update:pics', this.viewPic)
    }

  }
}

function arrayDelIndex(array, index) {
  var tmp = [];
  array.map(function (data, i) {
    if (i != index) {
      tmp.push(data)
    }
  })
  return tmp;
}
</script>

<style scoped>

</style>
